package com.zz.controller;
import com.zz.domain.StudentMachine;
import com.zz.service.HeartbeatService;
import com.zz.service.StudentMachineService;
import org.example.dto.StudentInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PrcController {
    @Autowired
    HeartbeatService heartbeatService;
    @Autowired
    StudentMachineService studentMachineService;

    // 处理来自学生机的ping消息
    @PostMapping("/student/select")
    public StudentInfoDTO select(@RequestBody StudentInfoDTO studentInfoDTo) {
        System.out.println("收到ping请求，machineId=" + studentInfoDTo.getMachineId()
                + ", ip=" + studentInfoDTo.getIp());
        StudentMachine machine = new StudentMachine();
        if (studentInfoDTo.getMachineId() != null || studentInfoDTo.getIp() != null) {
            machine.setMachineId(String.valueOf(studentInfoDTo.getMachineId()));
            machine.setIpAddress(studentInfoDTo.getIp());
            machine.setName(studentInfoDTo.getName());
            machine.setExamnumber(studentInfoDTo.getExamNumber());
            machine.setRegisterTime(new Date());
            machine.setStatus("online");
            machine.setLastHeartbeat(new Date());
            machine.setIsActive(true);
            studentMachineService.registerMachine(machine); // 调用registerMachine方法
        }
        studentInfoDTo.setOk("pong");
        return studentInfoDTo;
    }
    @GetMapping("/student/list")
    public List<StudentMachine> list() {
        return studentMachineService.getAllMachines();
    }
    /**
     * 获取在线人数
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Integer>> getDashboardStats() {
        Map<String, Integer> stats = new HashMap<>();
        stats.put("connectedCount", studentMachineService.getConnectedStudentCount());
        stats.put("submittedCount", studentMachineService.getSubmittedStudentCount());
        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(stats);
    }
}